package com.talent.codes.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import com.talent.cloud.core.exception.BusinessException;
import com.talent.cloud.core.util.FileUtil;
import com.talent.codes.model.Config;
import com.talent.codes.model.GasLabel;
import com.talent.codes.model.PrintSetting;

public class JsonConfigHelper {
    private static Logger logger = LoggerFactory.getLogger(JsonConfigHelper.class);
    private static Config config;
    protected static long version = 0;
    protected static long saveVersion = 1;
    protected static long updateVersion = 1;

    static {
        loadConfig();

        //TokenWebFilter.addExcludeUrls(new String[]{"/admin/config/**"});
    }

    public static <T> T jsonParse(String json, Class<T> clazz) {
        T obj = null;
        if (json != null && !"".equals(json)) {
            try {
                obj = JSON.parseObject(json, clazz);
            } catch (Exception e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return obj;
    }

    public static <T> String toFormatJson(T obj) {
        String json = null;
        if (obj != null) {
            try {
                json = JSON.toJSONString(obj, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteNulls);
            } catch (Exception e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return json;
    }

    public static void loadConfig(){
        String basePath = ".";
        String fileName = "config.json";

        String ctx = null;
        File cf = new File(basePath, fileName);
        if(cf.exists() && cf.isFile()){
            logger.info("==begin to load " + cf.getName());
            ctx = FileUtil.readFromFile(basePath, cf.getName(), "UTF-8");
        }else{
            logger.warn("加载配置错误，./" + fileName + "文件不存在");
        }

        if(ctx != null){
            config = jsonParse(ctx, Config.class);
        }else {
            config = initConfig();
            //String title = "五个字名　称"; // 36号字体， 0.0f 间隔
            ctx = toFormatJson(config);
            FileUtil.saveToFile(ctx, basePath, fileName, "utf-8");
        }
    }

    public static Config initConfig() {
        long startNo = Long.parseLong("217248100001");
        String title2 = "五个字名　称"; // 36号字体， 0.0f 间隔
        String title = "四字名称";
        String webSite = "https://qcheck.yoursite.com/product?number=";

        Config cfg = new Config();
        cfg.setTemplates(new LinkedHashMap<>());
        GasLabel label = new GasLabel(title, webSite).size(240, 240);
        label.titlePos(4,20, 110, 110).titleStyle("宋体", 46, .1f, 50);
        label.qrCodePos( 102, 4, 138, 138);
        label.barCodePos(-10, 144, 260, 65).barCodeStyle("宋体", 34);
        label.setName("四字名称");

        GasLabel label2 = new GasLabel(title2, webSite).size(240, 240);
        label2.titlePos(4,20, 110, 110).titleStyle("宋体", 32, .0f, 50);
        label2.qrCodePos( 102, 4, 138, 138);
        label2.barCodePos(-10, 144, 260, 65).barCodeStyle("宋体", 34);
        label2.setName("五字名称");

        cfg.getTemplates().put(label.getName(), label);
        cfg.getTemplates().put(label2.getName(), label2);


        PrintSetting page = new PrintSetting(240,240,  7);
        page.divide(true, false, true);
        page.idCtrl(987654321012l,8);

        PrintSetting page2 = new PrintSetting(240,240,  7);
        page2.divide(true, false, true);
        page2.idCtrl(217248101900l,22);
        cfg.setPrintSettings(new LinkedHashMap<>());
        cfg.getPrintSettings().put("四字名称", page);
        cfg.getPrintSettings().put("五字名称", page2);
        return cfg;
    }

    public static List<GasLabel> listLabels(){
        List<GasLabel> labels = new ArrayList<GasLabel>();
        List<String> names = new ArrayList<>();
        names.addAll(config.getTemplates().keySet());
        Collections.sort(names);
        for(String name : names){
            GasLabel label = config.getTemplates().get(name);
            labels.add(label);
        }
        return labels;
    }

    public static GasLabel getLabel(String name){
        GasLabel label = config.getTemplates().get(name);
        BusinessException.ASSERT.notNull(label,"标签不存在:" + name);
        return label;
    }

    public static boolean removeLabel(String name){
        GasLabel label = config.getTemplates().remove(name);
        config.getPrintSettings().remove(name);
        return label != null;
    }

    public static void updateLabel(GasLabel label) {
        config.getTemplates().put(label.getName(), label);
        updateVersion++;
        saveConfig(true);
    }

    public static void updatePrintSetting(String name, PrintSetting printSetting) {
        config.getPrintSettings().put(name, printSetting);
        updateVersion++;

        saveConfig(true);
    }

    public static PrintSetting getPrintSetting(String name){
        GasLabel label = getLabel(name);
        PrintSetting ps = config.getPrintSettings().get(name);
        if(ps == null){
            ps = new PrintSetting(label.getWidth(),label.getHeight(), 7);
            ps.idCtrl(987654321012l,8);
            ps.divide(true, false, true);
            updatePrintSetting(name, ps);
        }
        return ps;
    }

    public static void saveConfig(boolean force) {
        long newVersion = updateVersion;
        if(saveVersion!=newVersion || force){
            String basePath = ".";
            String fileName = "config.json";
            String ctx = toFormatJson(config);
            FileUtil.saveToFile(ctx, basePath, fileName, "utf-8");
            saveVersion=newVersion;
        }
    }

    public static void printSuccess(String name , long nextId){
        PrintSetting ps = getPrintSetting(name);
        ps.setFirstId(nextId);
        updateVersion++;

        saveConfig(true);
    }
}
